package com.example.test.conview.view.core;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.ArrayMap;

import com.puty.conputyutils.ArrayUtls;
import com.puty.conputyview.view.DrawArea;
import com.puty.conputyview.view.tool.Global;

import java.util.ArrayList;
import java.util.List;

public class TableElement extends Element {
    /**
     * //行数
     */
    public int rowcount = 3;
    /**
     * //列数
     */
    public int cellcount = 3;
    public float strokeWidth = 0.2f;
    Bitmap tempimg;
    public float mRowHeight = 0;
    public float mColumWidth = 0;
    /**
     *存放每行高度
     */
    public List<Float> rowHeights;
    /**
     * 存放每列宽度
     */
    public List<Float> columWidths;
    public ZoomHChangedListener mZoomHChangedListener;
    public ZoomWChangedListener mZoomWChangedListener;
    /**
     * //是否选择单元格（选中状态点击单元格）
     */
    public boolean selecting = false;
    /**
     * //被选中单元格信息（包括由单元格生成的合并单元格）
     */
    public String callarray = "";
    /**
     * //点击单元格信息
     */
    public StringBuilder downcallarray;
    /**
     * //上一个选中信息
     */
    public String lastcallarray = "";
    /**
     * //储存合并行
     */
    public ArrayMap<String, String> rowmap;
    /**
     * //储存合并列
     */
    public ArrayMap<String, String> colummap;
    /**
     * //表格合并的元素
     */
//    public ArrayList<TableMergeBean> mergeList;
    /**
     * //储存文本内容
     */
    public ArrayMap<String, String> contentmap;
    /**
     * //储存行间距
     */
    public ArrayMap<String, String> textRowmap;
    /**
     * //储存字符间距
     */
    public ArrayMap<String, String> textlinemap;
    /**
     * //储存文本字体大小
     */
    public ArrayMap<String, String> textsizemap;
    /**
     * //文本对齐方式：0：左对齐 1：居中 2：右对齐 3:拉伸
     */
    public ArrayMap<String, String> textModemap;
    /**
     * //储存文本加粗
     */
    public ArrayMap<String, String> textBmap;
    /**
     * //储存文本斜体
     */
    public ArrayMap<String, String> textImap;
    /**
     * //下划线
     */
    public ArrayMap<String, String> textUmap;
    /**
     * //删除线
     */
    public ArrayMap<String, String> textDmap;
    /**
     * //字体
     */
    public ArrayMap<String, Typeface> textFont;
    /**
     * //字体名字
     */
    public ArrayMap<String, String> textFontName;
    /**
     * //递变量
     */
    public ArrayMap<String, String> textDdStep;
    /**
     * //数据来源   0文本框输入  1excel表格数据
     */
    public ArrayMap<String, String> textInputMode;
    /**
     * //excel表格绑定行号
     */
    public ArrayMap<String, String> textExcelRowIndex;
    /**
     * //excel表格绑定列号
     */
    public ArrayMap<String, String> textExcelColIndex;
    /**
     * //excel表格绑定列名
     */
    public ArrayMap<String, String> textExcelSourceColName;
    /**
     * 行间距
     */
    public float textRowSpace = 0;
    /**
     * 自动换行 1 换行 0 不换行
     */
    public int autoBreak = 1;
    /**
     * 对齐模式 0 居左 1 居中 2 居右 3拉伸
     */
    public int textMode = 0;
    /**
     * 多选
     */
    public int isMunSelect = 0;


    public interface ZoomHChangedListener {
        void zoomRowH(int index, float num);
    }

    public interface ZoomWChangedListener {
        void zoomColumW(int index, float num);
    }

    public void setZoomHChangedListener(ZoomHChangedListener listener) {
        mZoomHChangedListener = listener;
    }

    public void setZoomWChangedListener(ZoomWChangedListener listener) {
        mZoomWChangedListener = listener;
    }

    public interface RowHColumWChangedListener {
        void rowHChanged(Float rowH);

        void columWChanged(Float columW);
    }

    //普通点击两次进行单元格操作
    @Override
    public void selecting() {
        if (this.isselected) {
            this.selecting = true;
        } else {
            this.selecting = false;
            callarray = "";
        }
    }

    //移动则取消单元格操作
    @Override
    public void selecting(boolean Boolean) {
        this.selecting = Boolean;
    }

    public interface OnSelecting {
        void onSelecting(String callarray);
    }

    OnSelecting onSelecting;

    public void setOnSelecting(OnSelecting onSelecting) {
        this.onSelecting = onSelecting;
    }


    //判断点击的单元格
    @Override
    public void selecting(float x, float y) {
        if (this.selecting) {
//            String callcontext = callcontext(x, y);
            lastcallarray = callarray;
//            if (callarray.indexOf(callcontext) == -1) {//判断是否选中
//                if (isMunSelect == 0) {//单选则清除其他选中单元格
//                    callarray = "";
//                }
////                while (DrawtableUtil.getmergecall(callarray, callcontext, rowmap, colummap, 1).length() > 0) {
////                    callcontext = DrawtableUtil.getmergecall(callarray, callcontext, rowmap, colummap, 1);
////                    callarray = callarray + callcontext;
////                }
//                if (onSelecting != null) {
//                    onSelecting.onSelecting(callarray);
//                }
//                LogUtils.i("选中单个表格元素111", callarray);
//            } else {
//                if (isMunSelect == 0) {//单选则清除其他选中单元格
//                    callarray = "";
//                }
//                while (DrawtableUtil.getmergecall(callarray, callcontext, rowmap, colummap, 2).length() > 0) {
//                    callcontext = DrawtableUtil.getmergecall(callarray, callcontext, rowmap, colummap, 2);
//                    if (callcontext != null && callcontext != "") {
//                        String[] call = null;
//                        String[] calllist = callcontext.split("\\|");
//                        for (int j = 0; j < calllist.length; j++) {
//                            if (calllist[j].length() > 2) {
//                                call = calllist[j].split(",");
//                                if (call.length < 2) continue;
//                                String daletecall = "|" + call[0] + "," + call[1];
//                                callarray = callarray.replace(daletecall, "");
//                            }
//                        }
//                        LogUtils.i("选中单个表格元素222", callarray);
//                    }
//                }
                if (onSelecting != null) {
                    onSelecting.onSelecting(callarray);
                }
//            }
            this.init();
            if (isMunSelect == 0) {//单选则选中单元格画图后取消单元格操作
                this.selecting = false;
            }
        }
    }

    //根据点击坐标转换单元格位置
//    public String callcontext(float x, float y) {
//        return DrawtableUtil.callcontext(x, y, this.top, this.left, rowcount, rowHeights, cellcount, columWidths,this.rate);
//    }


    @SuppressLint("NewApi")
    public TableElement(Context context, float w, float h, Label lb, boolean isCopy) {
        super(context,lb);
        super.type = 5;
        callarray = "";
        rowmap = new ArrayMap<String, String>();
        colummap = new ArrayMap<String, String>();
        contentmap = new ArrayMap<String, String>();
        textRowmap = new ArrayMap<String, String>();
        textlinemap = new ArrayMap<String, String>();
        textsizemap = new ArrayMap<String, String>();
        textModemap = new ArrayMap<String, String>();
        textBmap = new ArrayMap<String, String>();
        textImap = new ArrayMap<String, String>();
        textUmap = new ArrayMap<String, String>();
        textDmap = new ArrayMap<String, String>();
        textFont = new ArrayMap<String, Typeface>();
        textFontName = new ArrayMap<String, String>();
        textDdStep = new ArrayMap<String, String>();
        textInputMode = new ArrayMap<String, String>();
        textExcelRowIndex = new ArrayMap<String, String>();
        textExcelColIndex = new ArrayMap<String, String>();
        textExcelSourceColName = new ArrayMap<String, String>();
//        mergeList = new ArrayList<>();//表格合并的元素
        downcallarray = new StringBuilder();
        rowHeights = new ArrayList<>();
        columWidths = new ArrayList<>();
        /**
         * // 图像宽度
         * */
        super.width = w;
        /**
         * // 图像高度
         * */
        super.height = h;
        mRowHeight = height / rowcount;
        mColumWidth = width / cellcount;
        if (!isCopy) {//不是复制对象  我们就计算一下每个单元格的宽高
            for (int i = 0; i < rowcount; i++) {
                rowHeights.add(mRowHeight);
            }
            for (int i = 0; i < cellcount; i++) {
                columWidths.add(mColumWidth);
            }
        }

        if (lb.Width > lb.Height) {
            strokeWidth = lb.Height / 100f;
        } else {
            strokeWidth = lb.Width / 100f;
        }
        this.fontIndex = getFontIndex(2, mColumWidth / lb.scale / 8, mRowHeight / lb.scale / 8);
        setFontSize();
    }

    protected int getFontIndex(int contentLength, float w, float h) {
        float min = w > h ? h : w;
        float suiValue = min * 0.8f;
        float[] fontSize = new float[Global.fontSize.length];
        for (int i = 0;i<fontSize.length;i++){
            fontSize[i] = 3 * Global.fontSize[i];
        }
        int index = ArrayUtls.find(fontSize,0,fontSize.length-1,suiValue);
        return index;
    }

    public void setRow(int count) {
        int rowCount = rowcount;
        if (rowCount > count) {
            for (int i = rowCount; i > count; i--) {
                removeRow();
            }
        } else if (rowCount < count) {
            for (int i = count; i > rowCount; i--) {
                addRow();
            }
        }
    }

    /**
     * 添加新行
     */
    public void addRow() {
        if (rowcount + 1 <= 20) {
            mRowHeight = rowHeights.get(rowcount-1);
            rowHeights.add(mRowHeight);
            this.height += mRowHeight;
            rowcount++;
            init();
            DrawArea.dragView.invalidate();
            DrawArea.dragView.refreshImage();
        }
    }


    public void removeRow() {
        if (rowcount - 1 > 0) {
            this.height -= rowHeights.get(rowcount - 1);
            rowcount--;
            rowHeights.remove(rowcount);
            init();
            DrawArea.dragView.invalidate();
            DrawArea.dragView.refreshImage();
        }
    }

    public void setColum(int colum) {
        int cellCount = cellcount;
        if (cellCount > colum) {
            for (int i = cellCount; i > colum; i--) {
                removeColum();
            }
        } else if (cellCount < colum) {
            for (int i = colum; i > cellCount; i--) {
                addColum();
            }
        }
    }

    public void removeColum() {
        if (cellcount - 1 > 0) {
            this.width -= columWidths.get(cellcount - 1);
            cellcount--;
            columWidths.remove(cellcount);
            init();
            DrawArea.dragView.invalidate();
            DrawArea.dragView.refreshImage();
        }
    }

    /**
     * 添加新列
     */
    public void addColum() {
        if (cellcount + 1 <= 20) {
            mColumWidth = columWidths.get(cellcount-1);
            columWidths.add(mColumWidth);
            this.width += mColumWidth;
            cellcount++;
            init();
            DrawArea.dragView.invalidate();
            DrawArea.dragView.refreshImage();
        }
    }

    /**
     * 设置行高
     */
    public void setRowHeight(int row, float num, RowHColumWChangedListener listener) {
        for (int i = 0; i < rowHeights.size(); i++) {
            if (i == row) {
                //变化的行
                rowHeights.set(i, num);
                if (listener != null)
                    listener.rowHChanged(rowHeights.get(i));
                continue;
            }
        }
        initZoom();
        DrawArea.dragView.invalidate();
        DrawArea.dragView.refreshImage();
    }

    /**
     * 设置列宽
     */
    public void setColumWidth(int colum, float num, RowHColumWChangedListener listener) {
        for (int i = 0; i < columWidths.size(); i++) {
            if (i == colum) {
                //变化的行
                columWidths.set(i, num);
                if (listener != null) {
                    listener.columWChanged(columWidths.get(i));
                }
            }
        }
        initZoom();
        DrawArea.dragView.invalidate();
        DrawArea.dragView.refreshImage();
    }

    /*
     * 设置字体大小
     * */
    @Override
    public void setFontSize() {
        //字体大小
        float fz = Global.fontSize[Math.abs(fontIndex)] * 8 * lb.scale;
        this.fontSize = fz;
    }


    @Override
    public void init() {
        super.init();
        this.rate(this.rate);
    }

    public void initZoom() {
        this.rate(this.rate);
    }

    private void refreshColumnWidth() {//刷新列宽度
        float temporaryWidth = 0;
        float minSize = scale * 8;
        float mun = 0;

        List<Float> list = columWidths;
        if (this.rate == 90 || this.rate == 270) {
            list = rowHeights;
        }
        for (int i = 0; i < list.size(); i++) {
            temporaryWidth += list.get(i);
        }
        for (int i = 0; i < list.size(); i++) {
            Float aFloat = list.get(i);
            aFloat = aFloat / temporaryWidth * width;
            aFloat = aFloat < minSize ? minSize : aFloat;
            list.set(i, aFloat);
            if (this.rate == 90 || this.rate == 270) {
                if (mZoomHChangedListener != null) {
                    mZoomHChangedListener.zoomRowH(i, aFloat);
                }
            } else {
                if (mZoomWChangedListener != null) {
                    mZoomWChangedListener.zoomColumW(i, aFloat);
                }
            }
            mun += aFloat;
        }
        this.width = mun;
    }

    private void refreshRowHeight() {//刷新行高度
        float temporaryHeight = 0;
        float minSize = scale * 8;
        float mun = 0;
        List<Float> list = rowHeights;
        if (this.rate == 90 || this.rate == 270) {
            list = columWidths;
        }
        for (int i = 0; i < list.size(); i++) {
            temporaryHeight += list.get(i);
        }
        for (int i = 0; i < list.size(); i++) {
            Float aFloat = list.get(i);
            aFloat = aFloat / temporaryHeight * this.height;
            aFloat = aFloat < minSize ? minSize : aFloat;
            list.set(i, aFloat);
            if (this.rate == 90 || this.rate == 270) {
                if (mZoomWChangedListener != null) {
                    mZoomWChangedListener.zoomColumW(i, aFloat);
                }
            } else {
                if (mZoomHChangedListener != null) {
                    mZoomHChangedListener.zoomRowH(i, aFloat);
                }
            }
            mun += aFloat;
        }
        this.height = mun;
    }


    private void initView() {
        //重新计算宽高
        refreshColumnWidth();
        refreshRowHeight();

        float width = this.width;
        float height = this.height;
        //对调宽高及位置
        if (this.rate == 90 || this.rate == 270) {
            width = this.height;
            height = this.width;
        }

        Bitmap bmp = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(strokeWidth * 8 * scale);//外边矩形线宽//
        if(!isShow){
            paint.setStrokeWidth(strokeWidth * 8);//外边矩形线宽//
        }


        //画选中单元格
//        DrawtableUtil.drawselectcall(callarray, columWidths, rowHeights, paint, canvas);

        /**
         * // 先画矩形框
         * */
        paint.setColor(Color.BLACK);
        paint.setStyle(Style.STROKE);
        RectF rF = new RectF(strokeWidth * 4 * scale, strokeWidth * 4 * scale, width - strokeWidth * 4 * scale, height - strokeWidth * 4 * scale);
        if(!isShow){
            rF = new RectF(strokeWidth * 4 , strokeWidth * 4 , width - strokeWidth * 4, height - strokeWidth * 4 );
        }
        canvas.drawRect(rF, paint);

        //画文本内容
        /*for (int i = 1; i <= rowcount; i++) {//行
            for (int j = 1; j <= cellcount; j++) {//列
                int fontIndex = getFontIndex(2, columWidths.get(j - 1) / 8 / lb.scale, rowHeights.get(i - 1) / 8 / lb.scale);
//                LogUtils.i("字体下标", "宽：" + columWidths.get(i-1) / 8 / lb.scale + "  高:" + rowHeights.get(j-1) / 8 / lb.scale + "  下标:" + fontIndex);
                textsizemap.put(i + "," + j, "" + fontIndex);
            }
        }*/

        //画表格文本内容
//        DrawtableUtil.drawcontent(this, rowcount, cellcount, contentmap, textModemap, rowHeights, columWidths, canvas, lb);

        /**
         * // 画行线
         * */
        paint.setColor(Color.BLACK);
        paint.setStyle(Style.STROKE);
//        paint.setStrokeWidth(strokeWidth);
//        mRowHeight = h / rowcount;
        paint.setStrokeWidth(strokeWidth * 8 * scale);//里面线条宽
        if(!isShow){
            paint.setStrokeWidth(strokeWidth * 8 );//里面线条宽
        }


//        DrawtableUtil.drawrow(rowcount, rowmap, rowHeights, cellcount, canvas, columWidths, paint);

        // 画列
//        mColumWidth = w / cellcount;
//        DrawtableUtil.drawcolum(cellcount, colummap, columWidths, rowcount, canvas, rowHeights, paint);

        //旋转
        Matrix matrix = new Matrix();
        matrix.setRotate(this.rate, bmp.getWidth() / 2, bmp.getHeight() / 2);
        this.tempimg = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);

//        LogUtils.e("表格界面  字体大小  " + this.fontSize  + "  字间距 " + this.textCellSpace+ "  元素类型 " + this.type  + "  fontIndex "  +  this.fontIndex + "   width "  +  this.width + " height "  +  this.height + "标签的宽度" + lb.Width + "标签的高度" +  lb.Height);

    }


    @Override
    public void rate(int degree) {
        //缓存
        int tempDegree = degree;
        //旋转的角度
        degree = Math.abs(degree - this.rate);
        if (tempDegree == 0 && this.rate == 270) {
            degree = 90;
        }
        if (degree == 90) {
            //对调宽高及位置
            PointF center = new PointF(left + this.width / 2, top + this.height / 2);
            float temp = this.width;
            this.width = this.height;
            this.height = temp;
            this.left = center.x - this.width / 2;
            this.top = center.y - this.height / 2;


        }
        this.rate = tempDegree;
        if (mZoomHChangedListener != null) {
            for (int i = 0; i < rowHeights.size(); i++) {
                mZoomHChangedListener.zoomRowH(i, rowHeights.get(i));
            }
        }
        if (mZoomWChangedListener != null) {
            for (int i = 0; i < columWidths.size(); i++) {
                mZoomWChangedListener.zoomColumW(i, columWidths.get(i));
            }
        }
        initView();
    }

    @Override
    public void zoom(float x, float y, float w, float h) {
        super.zoom(x, y, w, h);
        float minSize = scale * 8;
        //往X方向
        if (this.zoomdirect == 0) {
            width += x;
            if (width <= minSize * cellcount) {
                width = minSize * cellcount;
            } else if (this.left + this.width + minSize >= w) {
                width -= x;
                return;
            }
            refreshColumnWidth();
        } else {
            height += y;
            if (height <= minSize * rowcount) {
                height = minSize * rowcount;
            } else if (this.top + this.height + minSize >= h) {
                height -= y;
                return;
            }
            refreshRowHeight();
        }
        this.initZoom();
        zoomOtherSelected(x, y);

//        字体自适应大小 TODO 还待优化
        for (int i = 1; i <= rowcount; i++) {//行
            for (int j = 1; j <= cellcount; j++) {//列
                int fontIndex = getFontIndex(2, columWidths.get(j - 1) / 8 / lb.scale, rowHeights.get(i - 1) / 8 / lb.scale);
//                LogUtils.i("字体下标", "宽：" + columWidths.get(i-1) / 8 / lb.scale + "  高:" + rowHeights.get(j-1) / 8 / lb.scale + "  下标:" + fontIndex);
                textsizemap.put(i + "," + j, "" + fontIndex);
            }
        }

    }

    public void draw(Canvas canvas) {
        super.draw(canvas);
        Rect sr = new Rect(0, 0, this.tempimg.getWidth(), this.tempimg.getHeight());
        canvas.drawBitmap(this.tempimg, sr, new RectF(left, top,
                left + width, top + height), null);

        if (isselected && isLock == 0) {
            //画缩放框
            //画右边缩放图标
            float hl = this.left + this.width - puhBitmap.getWidth() / 2;
            float ht = this.top + this.height / 2 - puhBitmap.getHeight() / 2;
            float hr = this.left + this.width + puhBitmap.getWidth() / 2;
            float hb = this.top + this.height / 2 + puhBitmap.getHeight() / 2;
            Rect rs = new Rect(0, 0, puhBitmap.getWidth(), puhBitmap.getHeight());
            RectF ds = new RectF(hl, ht, hr, hb);
            canvas.drawBitmap(puhBitmap, rs, ds, null);

            //画底部缩放图标
            hl = this.left + this.width / 2 - puvBitmap.getWidth() / 2;
            ht = this.top + this.height - puvBitmap.getHeight() / 2;
            hr = this.left + this.width / 2 + puvBitmap.getWidth() / 2;
            hb = this.top + this.height + puvBitmap.getHeight() / 2;
            rs = new Rect(0, 0, puvBitmap.getWidth(), puvBitmap.getHeight());
            ds = new RectF(hl, ht, hr, hb);
            canvas.drawBitmap(puvBitmap, rs, ds, null);

            //左上角删除图标
            hl = this.left - this.puvBitmap.getWidth() / 2;
            ht = this.top - this.puvBitmap.getHeight() / 2;
            hr = this.left + this.puvBitmap.getWidth() / 2;
            hb = this.top + this.puvBitmap.getHeight() / 2;
            rs = new Rect(0, 0, this.deleteBitmap.getWidth(), this.deleteBitmap.getHeight());
            ds = new RectF(hl, ht, hr, hb);
            canvas.drawBitmap(this.deleteBitmap, rs, ds, null);
        }
    }

    /**
     * 判断元素是否缩放
     */
    @Override
    public Element isscale(float x, float y) {
        //文本
        RectF rectF;
        float hl, ht, hr, hb;

        hl = this.left + this.width - scaleImageWidth / 2;
        ht = this.top + this.height / 2 - scaleImageWidth / 2;
        hr = this.left + this.width + scaleImageWidth / 2;
        hb = this.top + this.height / 2 + scaleImageWidth / 2;

        rectF = new RectF(hl, ht, hr, hb);
        if ((x >= rectF.left && x <= rectF.right) && (y >= rectF.top && y <= rectF.bottom)) {
            if(lb.isMunSelect == 1){//多选
                for (BaseElement e:lb.Elements) {
                    if(e.isselected){
                        e.zoomdirect = 0;
                    }
                }
            }else {
                this.zoomdirect = 0;//X方向
            }
            return this;
        }

        hl = this.left + this.width / 2 - scaleImageWidth / 2;
        ht = this.top + this.height - scaleImageWidth / 2;
        hr = this.left + this.width / 2 + scaleImageWidth / 2;
        hb = this.top + this.height + scaleImageWidth / 2;

        rectF = new RectF(hl, ht, hr, hb);
        if ((x >= rectF.left && x <= rectF.right) && (y >= rectF.top && y <= rectF.bottom)) {
            if(lb.isMunSelect == 1){//多选
                for (BaseElement e:lb.Elements) {
                    if(e.isselected){
                        e.zoomdirect = 1;
                    }
                }
            }else {
                this.zoomdirect = 1;//Y方向
            }
            return this;
        }
        return null;
    }

}
